import React, { useState } from 'react';
import { Modal, Spin, Form, TreeSelect, Select } from 'antd';
import ProForm, { ProFormSwitch, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { getTreeSelectData, getRoleTreeSelectData } from '../service';
import { useRequestHandle } from '@/utils/utils';
import { useUpdateEffect } from '@umijs/hooks';

const SaveForm = (props) => {
  const [positionTree, setPositionTree] = useState([]);
  const [roleSelectData, setRoleSelectData] = useState([]);
  const getTreeSelectHandler = useRequestHandle(getTreeSelectData, (data) => {
    setPositionTree(data);
  });
  const getRoleSelectHandler = useRequestHandle(getRoleTreeSelectData, (data) => {
    setRoleSelectData(data);
  });
  const { modalVisible, onCancel, onSubmit, loading, record } = props;

  useUpdateEffect(() => {
    if (modalVisible) {
      getTreeSelectHandler.run({});
      getRoleSelectHandler.run({});
    }
  }, [modalVisible]);

  return (
    <Modal
      destroyOnClose
      title={record.id ? '修改职位信息' : '新增职位信息'}
      open={modalVisible}
      onCancel={() => onCancel()}
      footer={null}
    >
      <Spin tip="正在处理..." spinning={loading}>
        <ProForm
          onFinish={async (value) => {
            const params = value;
            if (record.id) {
              params.id = record.id;
            }
            await onSubmit(params);
          }}
          initialValues={{ status: true, ...record }}
        >
          <ProFormText
            name="name"
            label="职位名称"
            fieldProps={{
              allowClear: true,
            }}
            placeholder="请输入职位名称"
            rules={[{ required: true, message: '请输入职位名称！' }]}
          />
          <ProFormTextArea
            name="remarks"
            label="备注"
            fieldProps={{
              allowClear: true,
            }}
            placeholder="请输入备注"
            rules={[{ required: true, message: '请输入备注！' }]}
          />
          <Form.Item name="parentId" label="上级职位" placeholder="请选择上级职位">
            <TreeSelect
              allowClear={true}
              style={{ width: '100%' }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              placeholder="默认为顶级职位"
              treeData={positionTree}
              treeDefaultExpandAll
            />
          </Form.Item>

          <Form.Item name="roleIds" label="角色" placeholder="请选择角色">
            <Select
              allowClear={true}
              mode="tags"
              placeholder="职位拥有的角色"
              options={roleSelectData}
            />
          </Form.Item>
          {!record.id && (
            <ProFormSwitch
              name="status"
              label="状态"
              checkedChildren="启用"
              unCheckedChildren="禁用"
            />
          )}
        </ProForm>
      </Spin>
    </Modal>
  );
};

export default SaveForm;
